import 'package:chatgreat/helper/ability.dart';
import 'package:chatgreat/helper/event.dart';
import 'package:chatgreat/helper/haptic_feedback.dart';
import 'package:chatgreat/lang/lang.dart';
import 'package:chatgreat/page/component/background_container.dart';
import 'package:chatgreat/page/component/theme/custom_theme.dart';
import 'package:chatgreat/repo/settings_repo.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localization/flutter_localization.dart';
import 'package:go_router/go_router.dart';

import '../helper/constant.dart';

// apptabbar页面
class AppScaffold extends StatefulWidget {
  final SettingRepository settingRepo;
  final StatefulNavigationShell navigationShell;
  const AppScaffold({
    Key? key,
    required this.settingRepo, required this.navigationShell,
  }) : super(key: key);
  @override
  State<AppScaffold> createState() => _AppScaffoldState();
}

class _AppScaffoldState extends State<AppScaffold> {
  var _showBottomNavigatorBar = true;

  Function? cancelHideBottomNavigatorBarEventListener;
  Function? cancelShowBottomNavigatorBarEventListener;

  @override
  void dispose() {
    cancelHideBottomNavigatorBarEventListener?.call();
    cancelShowBottomNavigatorBarEventListener?.call();

    super.dispose();
  }

  @override
  void initState() {
    cancelHideBottomNavigatorBarEventListener =
        GlobalEvent().on("hideBottomNavigatorBar", (data) {
          if (mounted) {
            setState(() {
              _showBottomNavigatorBar = false;
            });
          }
        });

    cancelShowBottomNavigatorBarEventListener =
        GlobalEvent().on("showBottomNavigatorBar", (data) {
          if (mounted) {
            setState(() {
              _showBottomNavigatorBar = true;
            });
          }
        });

    super.initState();
  }

  List<BottomNavigationBarConfig> _bottomNavigationBarList(
      {int? currentIndex}) {
    return [
      if (Ability().enableChat)
        BottomNavigationBarConfig(
          builder: (index, customColors) => createAnimatedNavBarItem(
            icon: 'home0.png',
            activatedIcon: 'home1.png',
            activatedColor: customColors.tabBarColor,
            label: AppLocale.chatAnywhere.getString(context),
            activated: currentIndex == index,
          ),
          route: '/chat-chat',
        ),
      if (Ability().enableCreationIsland)
        BottomNavigationBarConfig(
          builder: (index, customColors) => createAnimatedNavBarItem(
            icon: 'yingyong0.png',
            activatedIcon: 'yingyong1.png',
            activatedColor: customColors.tabBarColor,
            label: AppLocale.creativeIsland.getString(context),
            activated: currentIndex == index,
          ),
          route: '/creative-draw',
        ),
      if (Ability().enableGallery)
        BottomNavigationBarConfig(
          builder: (index, customColors) => createAnimatedNavBarItem(
            icon: 'huihua0.png',
            activatedIcon: 'huihua1.png',
            activatedColor: customColors.tabBarColor,
            label: AppLocale.discover.getString(context),
            activated: currentIndex == index,
          ),
          route: '/creative-gallery',
        ),
      if (Ability().enableDigitalHuman)
        BottomNavigationBarConfig(
          builder: (index, customColors) => createAnimatedNavBarItem(
            icon: 'zhuli0.png',
            activatedIcon: 'zhuli1.png',
            activatedColor: customColors.tabBarColor,
            label: AppLocale.homeTitle.getString(context),
            activated: currentIndex == index,
          ),
          route: '/',
        ),

      BottomNavigationBarConfig(
        builder: (index, customColors) => createAnimatedNavBarItem(
          icon: 'me0.png',
          activatedIcon: 'me1.png',
          activatedColor: customColors.tabBarColor,
          label: AppLocale.me.getString(context),
          activated: currentIndex == index,
        ),
        route: '/setting',
      ),
    ];
  }

  @override
  Widget build(BuildContext context) {
    final currentIndex = _calculateSelectedIndex(context);
    final customColors = Theme.of(context).extension<CustomColors>()!;
    final barItems = _bottomNavigationBarList(currentIndex: currentIndex);
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: BackgroundContainer(
        setting: widget.settingRepo,
        enabled: true,
        child: widget.navigationShell,
      ),
      extendBody: true, //启用透明
      bottomNavigationBar: currentIndex > -1 && _showBottomNavigatorBar
          ? BottomNavigationBar(
        landscapeLayout: BottomNavigationBarLandscapeLayout.centered,
        showSelectedLabels: true,
        showUnselectedLabels: true,
        currentIndex: _calculateSelectedIndex(context),
        onTap: (int index) => _onTap(context, index),
        selectedItemColor: customColors.tabBarColor,
        unselectedItemColor: const Color(0xFFA3A2AB),
        selectedFontSize: 11,
        unselectedFontSize: 11,
        type: BottomNavigationBarType.fixed,
        enableFeedback: true,
        backgroundColor: Colors.transparent,
        elevation: 0,
        items: [
          for (var i = 0; i < barItems.length; i++)
            barItems[i].builder(i, customColors),
        ],
      )
          : null,
    );
  }

  int _calculateSelectedIndex(BuildContext context) {
    final GoRouter route = GoRouter.of(context);
    final String location = route.location.split('?').first;

    final barItems = _bottomNavigationBarList();
    for (var i = 0; i < barItems.length; i++) {
      if (barItems[i].route == location) return i;
    }

    return -1;
  }

  void onTap(int value) {
    if (context.canPop()) {
      context.pop();
    }

    HapticFeedbackHelper.lightImpact();

    final barItems = _bottomNavigationBarList();
    if (value >= barItems.length) return context.go(Ability().homeRoute);

    return context.go(barItems[value].route);
  }
  void _onTap(BuildContext context, int index) {
    widget.navigationShell.goBranch(
      index,
      initialLocation: index == widget.navigationShell.currentIndex,
    );
    GlobalEvent().emit('refresh_$index');
    if (index != 0) {
      GlobalEvent().emit(HOME_CHAT_CLEAR_ONE_NOTIF);
    }
  }
}

BottomNavigationBarItem createAnimatedNavBarItem({
  String? label,
  bool activated = false,
  Color? activatedColor,
  required String icon,
  required String activatedIcon,
}) {
  return BottomNavigationBarItem(
    backgroundColor: Colors.transparent,
    label: label,
    icon: AnimatedCrossFade(
      firstChild: Image.asset('images/$icon'),
      secondChild: Image.asset('images/$activatedIcon'),
      crossFadeState:
      activated ? CrossFadeState.showSecond : CrossFadeState.showFirst,
      duration: const Duration(milliseconds: 300),
    ),
  );
}

class BottomNavigationBarConfig {
  final BottomNavigationBarItem Function(int index, CustomColors customColors)
  builder;
  final String route;

  BottomNavigationBarConfig({
    required this.builder,
    required this.route,
  });
}
